<template>
    <view :style="{height: 'calc(100vh - 110px)'}" style="overflow-y: scroll;">
        <j-cell-group :title="$t('General.home.myHome')" >
            <template v-for="(item, index) in groupList">
                <j-cell-slider
					v-if="item.isCreator"
					:key="item.id"
                    :title="item.groupName"
                    :tips="item.roomNum + $t('General.family.xRooms')+'  ' + item.deviceNum + $t('General.family.xDevices')"
                    :action="false"
                    @jftap="onBindtapGroup(item)"
                >
                    <view slot="action" style="height: 100%">
                        <view class="cell-action" @tap.stop.prevent="onBinddeleteGroup(item)">
                            {{ item.isCreator? $t('General.family.delete'): $t('General.family.exit')}}
                        </view>
                    </view>
                </j-cell-slider>
            </template>
        </j-cell-group>
		
		<j-cell-group :title="$t('General.family.joinedHome')" >
		    <template v-for="(item, index) in groupList">
		        <j-cell-slider
					v-if="!item.isCreator"
					:key="item.id"
		            :title="item.groupName"
		            :tips="item.roomNum + $t('General.family.xRooms') + ' ' + item.deviceNum + $t('General.family.xDevices')"
                    :action="false"
		            @jftap="onBindtapGroup(item)"
		        >
					<view v-if="item.creatorName" class="subTitle" slot="subTitle">
						{{$t('General.family.from')+item.creatorName}}
					</view>
                    <view slot="action" style="height: 100%">
                        <view class="cell-action" @tap.stop.prevent="onBinddeleteGroup(item)">
                            {{ item.isCreator? $t('General.family.delete'): $t('General.family.exit') }}
                        </view>
                    </view>
				</j-cell-slider>
		    </template>
		</j-cell-group>
    </view>
</template>

<script>
const {
		splitArray
	} = require('@/utils/util.js');
export default {
    data() {
        return {
            groupList: [],
            calcHeight: '40vh',
        };
    },
    watch: {
        groupList: {
            handler: function (res) {
                console.log('groupList 更新了！！！', res); //getApp().globalData.groupList = res

                uni.setStorageSync('groupList', res);
            },

            immediate: true,
            deep: true
        }
    },
	
	mounted: function() {
		// console.log('===header:mounted:');
		uni.$on('userGroupDel',this.RefreshUserGroupList);
	},
	
    beforeMount: function () {
        // 在组件实例进入页面节点树时执行
    },

    destroyed: function () {
        // 在组件实例被从页面节点树移除时执行
		uni.$off('userGroupDel',this.RefreshUserGroupList);
    },

    onPageShow: function () {
        // 页面被展示
        this.getUserGroupListByPage();
    },

    onPageHide: function () {
        // 页面被隐藏
    },

    onPageResize: function () {
        // 页面尺寸变化
    },

    /**
     * 组件的方法列表
     */
    methods: {
		// mqtt刷新家庭组列表
		RefreshUserGroupList(res){
			this.getUserGroupListByPage('Refresh')
		},
        // 查询用户组列表
        getUserGroupListByPage(type) {
            const data = {
                page: 1,
                limit: 999
            };
            getApp().globalData.api.getUserGroupListByPage(data, (result) => {
                console.log('查询用户组列表:', result);
				let sns = [];
                const groupList = result.data;
				groupList.forEach(item=>{
					sns.push(item.id)
					if(item.creatorName){
						item.familyName = item.creatorName.slice(0,10)+'的家庭'+'('+item.groupName+')'
					}else{
						item.familyName = item.groupName
					}
				})
				this.groupList = groupList;
				if(type){
					this.subscribeMqttInfo(sns)
				} 
                let index = 0
                groupList.forEach(item => {
                    if(item.isCreator) index++
                })
                this.calcHeight = 70 - index * 6 + 'vh'
            });
        },
		
		//mqtt订阅发送消息
		subscribeMqttInfo(sns) {
			let topic = [];
			sns.forEach((item) => {
				topic.push(`/group/${item}`)
			})
			// console.log(topic,'需要订阅的家庭数据')
			let arr = splitArray(topic, 20)
			if (arr.length > 0) {
				arr.forEach((item) => {
					getApp().globalData.mqtt.subscribe(item)
				})
			}
		},

        // 点击跳转到家庭详情
        onBindtapGroup(ev) {
            console.log('onBindmytapGroup:', ev);
            let group = ev
            uni.navigateTo({
                url: `/jvss/pagesDevice/group/group-info/group-info?group=${JSON.stringify(group)}`
            });
        },

        // 删除家庭组-1
        onBinddeleteGroup(ev) {
            console.log('onBinddeleteGroup:', ev);
			if(!ev.isCreator){
				// 直接删除
				this.delCurrentUserGroup(ev)
			}else{
				let isCreatorList = []
				this.groupList.forEach(item => {
					if(item.isCreator){
						isCreatorList.push(item)
					}
				})
				if(isCreatorList.length <= 1){
					uni.showModal({
						title: this.$t('General.family.tip'),
						content: this.$t('General.family.msg6'),
						showCancel:false
					});
				}else{
					//删除数据
					this.delUserGroup(ev)
				}
			} 
        },
		// 删除家庭组-2
		delUserGroup(ev){
			const data = {
			    id: ev.id
			};
			uni.showModal({
			    title: this.$t('General.family.tip'),
			    content: this.$t('General.family.msg7'),
			    success: (res) => {
			        if (res.confirm) {
			            console.log('用户点击确定');
			            getApp().globalData.api.delUserGroup(data, (result) => {
			                uni.showToast({
			                    title: this.$t('General.family.msg8'),
			                    success: (res) => {
			                        this.getUserGroupListByPage();
			                    }
			                });
			            });
			        } else if (res.cancel) {
			            console.log('用户点击取消');
			        }
			    }
			});
		},
		// 删除其他家庭组
		delCurrentUserGroup(ev){
			uni.showLoading({
				mask:true
			})
			let data = {userGroupId: ev.id}
			getApp().globalData.api.delCurrentUserGroup(data, (result) => {
				uni.hideLoading()
			    uni.showToast({
			        title: this.$t('General.family.msg9'),
			        success: (res) => {
			            this.getUserGroupListByPage();
			        }
			    });
			});
		}
    }
};
</script>
<style lang="scss">
	.subTitle{
		color: #999;
		font-size: 24rpx;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		width: 50vw;
	}
    .cell-action {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #f4310a;
        font-size: 26rpx;
        /* padding: 0 40rpx; */
        width: 80px;
        margin-left: 1px;
    }
</style>